package com.rbmh.network.utils;

import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class WordDocumentExample {
    public static void main1(String[] args) {
//        String filePath = "C:\\Users\\Administrator\\Desktop\\XX县人社局工作介绍信某某.doc";
        String filePath = "C:\\Users\\Administrator\\Desktop\\XX县人社局工作介绍信某某.doc";

        // 创建新文档
//        WordDocumentHandler.createWordDocument(filePath, "这是一个示例文档内容。");

        // 读取文档
//        String content = WordDocumentHandler.readWordDocument(filePath);
//        System.out.println("文档内容: " + content);

        // 修改文档
//        WordDocumentHandler.modifyWordDocument(filePath, "示例", "修改后的");

        // 再次读取查看修改结果
//        content = WordDocumentHandler.readWordDocument(filePath);
//        System.out.println("修改后内容: " + content);

        // 添加图片（需要准备一张图片）
        // WordDocumentHandler.addImageToDocument(filePath, "image.jpg");


            // 支持 .doc 和 .docx 两种格式
            String docxFilePath = "C:\\Users\\Administrator\\Desktop\\测试.docx";
            String docFilePath = "C:\\Users\\Administrator\\Desktop\\XX县人社局工作介绍信某某.doc";

            // 创建新文档（默认创建 .docx）
//            WordDocumentHandler.createWordDocument(docxFilePath, "这是一个示例文档内容。");

            // 读取 .docx 文档
            String content = WordDocumentHandler.readWordDocument(docxFilePath);
            System.out.println("DOCX 文档内容: " + content);

            // 修改 .docx 文档
            WordDocumentHandler.modifyWordDocument(docxFilePath, "888", "080");

            // 获取文档信息
            WordDocumentHandler.getDocumentInfo(docxFilePath);

            // 如果是 .doc 文件
            // String docContent = WordDocumentHandler.readWordDocument(docFilePath);
            // System.out.println("DOC 文档内容: " + docContent);

            System.out.println("所有操作完成！");
    }

    public static void main23(String[] args) {
        String filePath = "C:\\Users\\Administrator\\Desktop\\测试.docx";

        // 方法1：直接针对你的运行结构进行处理（推荐先尝试这个）
        System.out.println("=== 方法1：精确处理运行结构 ===");
//        WordDocumentHandler.fixSpecific080Case(filePath);

        // 方法2：简单替换
        System.out.println("\n=== 方法2：简单替换 ===");
//        WordDocumentHandler.simpleReplaceSplitNumber(filePath);

        // 方法3：通用数字替换
        System.out.println("\n=== 方法3：通用数字替换 ===");
//        WordDocumentHandler.replaceNumberInRuns(filePath, "080", "081");

        // 方法4：如果上述方法都不行，使用调试模式
        System.out.println("\n=== 方法4：调试模式 ===");
        debugAndFix(filePath);
    }

        public static void main(String[] args) {
            String filePath = "C:\\Users\\Administrator\\Desktop\\测试.docx";

            // 方法1：精确替换（推荐）
//            System.out.println("=== 方法1：精确替换 ===");
            WordDocumentHandler.replaceTextWithStyle(filePath, "080", "081");

            // 方法2：专门处理人事调干字号
//            System.out.println("\n=== 方法2：专门处理 ===");
//            WordDocumentHandler.replacePersonnelNumberWithStyle(filePath);

            // 方法3：高级替换（最大限度保留样式）
//            System.out.println("\n=== 方法3：高级替换 ===");
//            WordDocumentHandler.advancedReplaceWithStyle(filePath);

            // 方法4：如果上述方法都不行，使用逐个运行替换
//            System.out.println("\n=== 方法4：逐个运行替换 ===");
//            replaceInSpecificRuns(filePath);
        }

        /**
         * 针对特定运行进行替换（最精确的方法）
         */
        private static void replaceInSpecificRuns(String filePath) {
            try (FileInputStream fis = new FileInputStream(filePath);
                 XWPFDocument document = new XWPFDocument(fis)) {

                // 先调试查看运行结构
                System.out.println("文档结构分析:");
                for (XWPFParagraph para : document.getParagraphs()) {
                    String paraText = para.getText();
                    if (paraText.contains("080") || paraText.contains("人事调干")) {
                        System.out.println("相关段落: " + paraText);
                        List<XWPFRun> runs = para.getRuns();
                        for (int i = 0; i < runs.size(); i++) {
                            XWPFRun run = runs.get(i);
                            String runText = run.getText(0);
                            if (runText != null) {
                                System.out.println("  运行 " + i + ": '" + runText + "'");
                                if (runText.contains("080")) {
                                    // 直接在这个运行中替换
                                    String newText = runText.replace("080", "081");
                                    run.setText(newText, 0);
                                    System.out.println("    已替换: 080 -> 081");
                                }
                            }
                        }
                    }
                }

                try (FileOutputStream out = new FileOutputStream(filePath)) {
                    document.write(out);
                    System.out.println("精确替换完成！");
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    /**
     * 专门处理拆分数字的情况
     * @param filePath 文档路径
     */
    public static void replaceSplitNumber(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            boolean modified = false;

            // 处理段落
            for (XWPFParagraph para : document.getParagraphs()) {
                if (replaceSplitNumberInParagraph(para)) {
                    modified = true;
                }
            }

            // 处理表格
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph para : cell.getParagraphs()) {
                            if (replaceSplitNumberInParagraph(para)) {
                                modified = true;
                            }
                        }
                    }
                }
            }

            if (modified) {
                try (FileOutputStream out = new FileOutputStream(filePath)) {
                    document.write(out);
                    System.out.println("拆分数字替换完成！");
                }
            } else {
                System.out.println("未找到需要替换的拆分数字");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在段落中处理拆分数字
     */
    private static boolean replaceSplitNumberInParagraph(XWPFParagraph para) {
        List<XWPFRun> runs = para.getRuns();
        String fullText = getFullTextFromRuns(runs);

        // 检查是否包含目标模式
        if (fullText.contains("新干人事调干字（2025）第") && fullText.contains("号")) {
            System.out.println("找到相关段落: " + fullText.trim());

            // 查找数字部分的位置
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.getText(0);

                if (runText != null && runText.matches(".*\\d+.*")) {
                    System.out.println("检查运行 " + i + ": '" + runText + "'");

                    // 检查这个运行和后续运行是否组成080
                    if (isNumberSplitAcrossRuns(runs, i, "080")) {
                        System.out.println("找到拆分的080数字");
                        replaceSplitNumberSequence(runs, i, "080", "081");
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * 检查数字是否被拆分 across multiple runs
     */
    private static boolean isNumberSplitAcrossRuns(List<XWPFRun> runs, int startIndex, String targetNumber) {
        StringBuilder numberBuilder = new StringBuilder();

        for (int i = startIndex; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.getText(0);

            if (runText != null) {
                // 提取数字部分
                String digits = runText.replaceAll("[^0-9]", "");
                numberBuilder.append(digits);

                // 如果已经构建的数字超过目标长度，退出
                if (numberBuilder.length() >= targetNumber.length()) {
                    break;
                }
            }
        }

        return numberBuilder.toString().equals(targetNumber);
    }

    /**
     * 替换被拆分的数字序列
     */
    private static void replaceSplitNumberSequence(List<XWPFRun> runs, int startIndex, String oldNumber, String newNumber) {
        int numberIndex = 0;
        int newNumberIndex = 0;

        for (int i = startIndex; i < runs.size() && numberIndex < oldNumber.length(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.getText(0);

            if (runText != null) {
                // 提取数字字符
                StringBuilder digitsInRun = new StringBuilder();
                for (char c : runText.toCharArray()) {
                    if (Character.isDigit(c)) {
                        digitsInRun.append(c);
                    }
                }

                if (null != digitsInRun && digitsInRun.length() > 0) {
                    // 构建新文本：用新数字替换旧数字
                    StringBuilder newRunText = new StringBuilder();
                    boolean inNumberSection = false;
                    StringBuilder currentDigits = new StringBuilder();

                    for (char c : runText.toCharArray()) {
                        if (Character.isDigit(c)) {
                            if (!inNumberSection) {
                                inNumberSection = true;
                                currentDigits.setLength(0);
                            }
                            currentDigits.append(c);
                        } else {
                            if (inNumberSection) {
                                // 处理数字部分
                                String originalDigits = currentDigits.toString();
                                if (originalDigits.equals(oldNumber.substring(numberIndex,
                                        Math.min(numberIndex + originalDigits.length(), oldNumber.length())))) {
                                    // 替换数字
                                    String replacement = newNumber.substring(newNumberIndex,
                                            Math.min(newNumberIndex + originalDigits.length(), newNumber.length()));
                                    newRunText.append(replacement);

                                    numberIndex += originalDigits.length();
                                    newNumberIndex += replacement.length();
                                } else {
                                    newRunText.append(originalDigits);
                                }
                                inNumberSection = false;
                            }
                            newRunText.append(c);
                        }
                    }

                    // 处理末尾的数字
                    if (inNumberSection) {
                        String originalDigits = currentDigits.toString();
                        if (originalDigits.equals(oldNumber.substring(numberIndex,
                                Math.min(numberIndex + originalDigits.length(), oldNumber.length())))) {
                            String replacement = newNumber.substring(newNumberIndex,
                                    Math.min(newNumberIndex + originalDigits.length(), newNumber.length()));
                            newRunText.append(replacement);

                            numberIndex += originalDigits.length();
                            newNumberIndex += replacement.length();
                        } else {
                            newRunText.append(originalDigits);
                        }
                    }

                    run.setText(newRunText.toString(), 0);

                    // 如果已经处理完所有数字，退出
                    if (numberIndex >= oldNumber.length()) {
                        break;
                    }
                }
            }
        }
    }

    /**
     * 更简单的方法：直接重建整个数字部分
     */
    public static void simpleReplaceSplitNumber(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            for (XWPFParagraph para : document.getParagraphs()) {
                String fullText = para.getText();
                if (fullText.contains("新干人事调干字（2025）第080号")) {
                    System.out.println("找到目标段落: " + fullText.trim());

                    // 找到包含数字的运行
                    List<XWPFRun> runs = para.getRuns();
                    int numberStartIndex = -1;
                    int numberEndIndex = -1;

                    // 找出数字运行的起始和结束位置
                    for (int i = 0; i < runs.size(); i++) {
                        XWPFRun run = runs.get(i);
                        String runText = run.getText(0);
                        if (runText != null && runText.matches(".*\\d.*")) {
                            if (numberStartIndex == -1) {
                                numberStartIndex = i;
                            }
                            numberEndIndex = i;
                        }
                    }

                    if (numberStartIndex != -1 && numberEndIndex != -1) {
                        // 清除数字部分的所有运行
                        for (int i = numberStartIndex; i <= numberEndIndex; i++) {
                            runs.get(i).setText("", 0);
                        }

                        // 在第一个数字运行位置插入新数字
                        runs.get(numberStartIndex).setText("081", 0);

                        System.out.println("已替换080为081");
                    }
                }
            }

            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 最直接的方法：重建整个文本但保留样式
     */
    public static void rebuildTextWithStyle(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            for (XWPFParagraph para : document.getParagraphs()) {
                String fullText = para.getText();
                if (fullText.contains("080")) {
                    String newText = fullText.replace("080", "081");

                    // 保留第一个运行的样式
                    List<XWPFRun> runs = para.getRuns();
                    if (!runs.isEmpty()) {
                        // 清空所有运行
                        for (XWPFRun run : runs) {
                            run.setText("", 0);
                        }
                        // 用第一个运行的样式设置新文本
                        runs.get(0).setText(newText, 0);
                    }
                }
            }

            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
                System.out.println("文本重建完成！");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从运行中获取完整文本
     */
    private static String getFullTextFromRuns(List<XWPFRun> runs) {
        StringBuilder sb = new StringBuilder();
        for (XWPFRun run : runs) {
            String text = run.getText(0);
            if (text != null) {
                sb.append(text);
            }
        }
        return sb.toString();
    }

    /**
     * 调试并修复
     */
    private static void debugAndFix(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            // 先调试查看结构
            System.out.println("调试信息:");
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (int i = 0; i < paragraphs.size(); i++) {
                XWPFParagraph para = paragraphs.get(i);
                String paraText = para.getText().trim();

                if (paraText.contains("新干人事调干字")) {
                    System.out.println("找到相关段落 " + i + ": " + paraText);

                    List<XWPFRun> runs = para.getRuns();
                    for (int j = 0; j < runs.size(); j++) {
                        XWPFRun run = runs.get(j);
                        String runText = run.getText(0);
                        if (runText != null && !runText.trim().isEmpty()) {
                            System.out.println("  运行 " + j + ": '" + runText + "'");

                            // 如果找到包含080的运行，直接替换
                            if (runText.contains("080")) {
                                String newText = runText.replace("080", "081");
                                run.setText(newText, 0);
                                System.out.println("    已替换: 080 -> 081");
                            }
                        }
                    }
                }
            }

            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
                System.out.println("调试修复完成！");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
